package com.probiz.estore.common.service.impl;


import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.product.ProductSku;
import com.probiz.estore.common.service.ProductService;
import com.probiz.estore.eai.exception.EaiException;
import com.probiz.estore.eai.product.generated.Inventory;
import com.probiz.estore.exception.OutOfStockException;
import com.probiz.estore.exception.ProductNoExistException;
import com.probiz.estore.exception.UnderMinimumPurchaseQuantityException;
import com.probiz.estore.product.service.ProdMainManager;
import com.probiz.estore.product.service.ProductManager;
import com.probiz.estore.product.service.ProductSkuManager;

public class ProductServiceImpl implements ProductService{
	private ProductManager productManager;
	private ProductSkuManager productSkuManager;
	private ProdMainManager prodMainManager;
	
	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}

	public void setProductSkuManager(ProductSkuManager productSkuManager) {
		this.productSkuManager = productSkuManager;
	}
	

	public void setProdMainManager(ProdMainManager prodMainManager) {
		this.prodMainManager = prodMainManager;
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProductService#getById(java.lang.Integer)
	 */
	public Product getById(Integer productId){
		return productManager.getById(productId);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProductService#getProductSkuByProductSkuCode(java.lang.String)
	 */
	public ProductSku getProductSkuByProductSkuCode(String productSkuCode){
		return productSkuManager.getProductSkuByProductSkuCode(productSkuCode);
	}
	
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#getProductSkuPojoByProductSkuCode(java.lang.String)
	 */
	public ProductSku getProductSkuPojoByProductSkuCode(String productSkuCode) {
		return productSkuManager.getProductSkuPojoByProductSkuCode(productSkuCode);
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProductService#getProductsByCategoryAndDisplayFlag(java.lang.Integer, java.lang.Short, int)
	 */
	public List<Product> getProductsByCategoryAndDisplayFlag(final Integer categoryId,final Short displayFlag,final int size){
		return productManager.getProductsByCategoryAndDisplayFlag(categoryId, displayFlag, size);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.product.service.ProductService#doIncreaseOneBuyTimes(java.lang.Integer)
	 */
	public void doIncreaseOneBuyTimes(Integer productId){
		prodMainManager.doIncreaseOneBuyTimes(productId);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#doUpdateStatBuyCount(java.lang.Integer, java.lang.Integer)
	 */
	public void doUpdateStatBuyCount(Integer productId,Integer buyCount){
		prodMainManager.doUpdateStatBuyCount(productId,buyCount);
	}
	
	public boolean isInCategoryBySku(Integer productSkuId, Integer categoryId) {
		ProductSku sku = productSkuManager.getById(productSkuId);
		boolean state = false;
		if (sku != null && sku.getProduct() != null) {
			ProductCategory category = sku.getProduct().getCategory();
			if (category != null) {
				String categoryPath = "."+category.getCategoryPath();
				if (categoryPath.contains("."+categoryId+".")) {
					state = true;
				}
			}
		}
		return state;
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#doImportProductForEai(com.probiz.estore.eai.product.generated.Inventory)
	 */
	public void doImportProductForEai(Inventory inventory) throws EaiException {
		
//		Product product = productManager.getProductByProductCode(inventory.getHeader().getCode());
//		Category category = categoryManager.getCategoryByCode(Constants.CATEGORY_TYPE_CATALOG, inventory.getHeader().getSortCode());
//		
//		//start:新产品初始化：产品实体
//		if(null == product){
//			product = new Product();
//			product.setProductCode(inventory.getHeader().getCode());
//			product.setStatus(Product.STATUS_ACTIVE);
//			product.setAvailabilityRule(ProductConstants.PRODUCT_AVAILABILITY_ALWAYS_SELL);
//			product.setProductKind(ProductConstants.PRODUCT_KIND_COMMON);
//			product.setIsAllowReview(Constants.FLAG_TRUE);
//			product.setMinOrderQuantity(1);
//		}
//		//end:新产品初始化：产品实体
//		
//		//start:产品名称	
//		product.setProductName(inventory.getHeader().getName());
//		//end:产品名称	
//		
//		//start:销售计量单位名称
//		if(StringUtils.isNotBlank(inventory.getHeader().getSaunitName())){
//			product.setSalesMeasureUnitName(inventory.getHeader().getSaunitName());
//		}else if(StringUtils.isNotBlank(inventory.getHeader().getCcomunitname())){
//			product.setSalesMeasureUnitName(inventory.getHeader().getCcomunitname());
//		}else{
//			product.setSalesMeasureUnitName("");
//		}
//		//end:销售计量单位名称
//		
//		//start:重量计量单位名称
//		if(StringUtils.isNotBlank(inventory.getHeader().getCWUnit())){
//			Unit unit = UnitEaiHelper.getInstance().getUnitByCode(inventory.getHeader().getCWUnit());
//			if(null != unit){
//				product.setWeightMeasureUnitName(unit.getName());
//			}else{
//				throw new EaiException("EAI Unit 不存在对应的计量单位:"+inventory.getHeader().getCWUnit());
//			}
//		}else{
//			product.setWeightMeasureUnitName("");
//		}
//		//end:重量计量单位名称
//		
//		//start:销项税率
//		if(StringUtils.isNotBlank(inventory.getHeader().getTaxRate())){
//			product.setTaxRate(new BigDecimal(inventory.getHeader().getTaxRate()));
//		}else{
//			product.setTaxRate(new BigDecimal(0));
//		}
//		//end:销项税率
//		
//		//start:产品状态
//		if(StringUtils.isNotBlank(inventory.getHeader().getFRetailPrice())){
//			product.setStatus(Product.STATUS_ACTIVE);
//		}else{
//			product.setStatus(Product.STATUS_NOTACTIVE);
//		}
//		//end:产品状态
//		
//		//start:第一次保存产品
//		productManager.save(product);
//		//end:第一次保存产品
//		
//		ProductSku defaultProductSku = product.getDefaultProductSku();
//		
//		//start:新产品初始化：默认SKU
//		if(null == defaultProductSku){
//			defaultProductSku = new ProductSku();
//			defaultProductSku.setProduct(product);
//			defaultProductSku.setSkuKind(ProductConstants.SKU_KIND_ENTITY);
//			defaultProductSku.setStatus(Constants.FLAG_TRUE);
//		}
//		//end:新产品初始化：默认SKU
//		
//		//start:SKU编码
//		defaultProductSku.setProductSkuCode(inventory.getHeader().getCode());
//		//end:SKU编码
//		
//		//start:长
//		if(StringUtils.isNotBlank(inventory.getHeader().getFLength())){
//			defaultProductSku.setLength(new BigDecimal(inventory.getHeader().getFLength()));
//		}else{
//			defaultProductSku.setLength(null);
//		}
//		//end:长
//		//start:宽
//		if(StringUtils.isNotBlank(inventory.getHeader().getFWidth())){
//			defaultProductSku.setWidth(new BigDecimal(inventory.getHeader().getFWidth()));
//		}else{
//			defaultProductSku.setWidth(null);
//		}
//		//end:宽
//		//start:高
//		if(StringUtils.isNotBlank(inventory.getHeader().getFHeight())){
//			defaultProductSku.setHeight(new BigDecimal(inventory.getHeader().getFHeight()));
//		}else{
//			defaultProductSku.setHeight(null);
//		}
//		//end:高
//		//start:零售价格
//		if(StringUtils.isNotBlank(inventory.getHeader().getFRetailPrice())){
//			defaultProductSku.setPrice(new BigDecimal(inventory.getHeader().getFRetailPrice()));
//		}else{
//			defaultProductSku.setPrice(null);
//		}
//		//end:零售价格
//		
//		//start:SKU状态
//		defaultProductSku.setStatus(product.getStatus());
//		//end:SKU状态
//		
//		//start:保存默认SKU
//		productSkuManager.save(defaultProductSku);
//		//end:保存默认SKU
//		
//		//start:设置默认SKU
//		product.setDefaultProductSku(defaultProductSku);
//		//end:设置默认SKU
//		
//		//start:新产品初始化：产品描述实体
//		if(null == product.getProductDescription()){
//			ProductDescription productDescription = new ProductDescription();
//			productDescriptionManager.save(productDescription);
//			product.setProductDescription(productDescription);
//		}
//		//end:新产品初始化：产品描述实体
//		
//		//start:新产品初始化:产品统计实体
//		if(null == productStatManager.getProductStatByProduct(product.getProductId())){
//			ProductStat productStat = new ProductStat();
//			productStat.setProduct(product);
//			productStat.setAverageRate(new BigDecimal(0));
//			productStat.setBuyCount(0);
//			productStat.setReviewCount(0);
//			productStatManager.save(productStat);
//			
//		}
//		//end:新产品初始化:产品统计实体
//		
//		//start:第二次保存产品
//		productManager.save(product);
//		//end:第二次保存产品
//		
//		//start:产品目录
//		List<Integer> categoryIdList = new ArrayList<Integer>();
//		for(ProductCategory minorCategory: product.getProductCategorys()){
//			categoryIdList.add(minorCategory.getCategoryId());
//		}
//		if(null != category){
//			productMainManager.saveProductCategories(product,  category.getCategoryId(), categoryIdList.toArray(new Integer[0]));
//		}else{
//			throw new EaiException("EAI inventory 不存在关联目录:"+inventory.getHeader().getSortCode());
//		}
//		//end:产品目录
//			
//		//start:批发价
//		WholesalePrice wholesalePrice = null;
//		if(StringUtils.isNotBlank(inventory.getHeader().getRefSalePrice())){
//			wholesalePrice = wholesalePriceManager.getSalePriceBySkuIdByMinQuantity(defaultProductSku.getProductSkuId(),new Integer(2));
//			if(null != wholesalePrice){
//				wholesalePrice.setPrice(new BigDecimal(inventory.getHeader().getRefSalePrice()));
//			}else{
//				wholesalePrice = new WholesalePrice();
//				wholesalePrice.setProductSku(defaultProductSku);
//				wholesalePrice.setPrice(new BigDecimal(inventory.getHeader().getRefSalePrice()));
//				wholesalePrice.setMinQuantity(new Integer(2));
//			}
//			wholesalePriceManager.save(wholesalePrice);
//		}else{
//			wholesalePrice = wholesalePriceManager.getSalePriceBySkuIdByMinQuantity(defaultProductSku.getProductSkuId(),new Integer(2));
//			if(null != wholesalePrice){
//				wholesalePriceManager.deleteById(wholesalePrice.getWholesalePriceId());
//			}else{
//			}
//		}
//		//end:批发价
//		logger.info("导入：inventory [name:"+inventory.getHeader().getName()+",code:"+inventory.getHeader().getCode()+"]");
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#doImportProductsForEai(java.util.List)
	 */
	public void doImportProductsForEai(List<Inventory> inventoryList)
			throws EaiException {
		//新增或者修改
		for(Inventory inventory : inventoryList){
			doImportProductForEai(inventory);
		}
	
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#checkMinPurchaseQuantity(java.lang.String, java.lang.Integer)
	 */
	public void checkMinPurchaseQuantity(String productSkuCode, Integer quantity) throws UnderMinimumPurchaseQuantityException{
		ProductSku productSku = getProductSkuByProductSkuCode(productSkuCode);
		if (quantity < 1) {
			throw new UnderMinimumPurchaseQuantityException(productSku, quantity);
		}
		if (productSku != null && productSku.getInventory() != null) {
			Integer minQuantity = productSku.getProduct().getMinOrderQuantity();
			if (minQuantity != null && minQuantity > quantity) {
				throw new UnderMinimumPurchaseQuantityException(productSku, quantity);
			}
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#checkInventory(java.lang.String, java.lang.Integer)
	 */
	public void checkInventory(String productSkuCode, Integer quantity) throws OutOfStockException {
		ProductSku productSku = getProductSkuByProductSkuCode(productSkuCode);
		if (productSku != null && productSku.getInventory() != null) {
			Integer availableQuantity = productSku.getInventory().getAvailableQuantity();
			if (availableQuantity != null && availableQuantity < quantity) {
				throw new OutOfStockException(productSku,availableQuantity);
			}
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.common.service.ProductService#checkBuyQuantity(java.lang.String, java.lang.Integer)
	 */
	public void checkBuyQuantity(String productSkuCode, Integer quantity) throws UnderMinimumPurchaseQuantityException, OutOfStockException{
		checkMinPurchaseQuantity(productSkuCode,quantity);
		checkInventory(productSkuCode,quantity);
	}

	/**
	 * 用于验证：加入购物车如果有配件缺货。
	 * 
	 * */
	public ProductSku checkInventoryError(String productSkuCode, Integer quantity) {
		ProductSku productSku = getProductSkuByProductSkuCode(productSkuCode);
		if (productSku != null && productSku.getInventory() != null) {
			Integer availableQuantity = productSku.getInventory().getAvailableQuantity();
			if (availableQuantity != null && availableQuantity < quantity) {
				return productSku;
			}
		}
		return null;
	}

	public void checkProductIsExist(String productSkuCode, String [] childrens) throws ProductNoExistException {
		if (StringUtils.isNotEmpty(productSkuCode)) {
			ProductSku productSku = getProductSkuByProductSkuCode(productSkuCode);
			if (productSku == null || productSku.getProduct() == null || !Product.STATUS_ACTIVE.equals(productSku.getProduct().getStatus())) {
				throw new ProductNoExistException();
			}
		}
		if (childrens != null && childrens.length > 0) {
			for (String code :childrens) {
				if (StringUtils.isNotEmpty(code)) {
					ProductSku childSku = getProductSkuByProductSkuCode(code);
					if (childSku == null || childSku.getProduct() == null || !Product.STATUS_ACTIVE.equals(childSku.getProduct().getStatus())) {
						throw new ProductNoExistException();
					}
				}
			}
		}
	}
}
